package com.shawn.springboot.integeration.redis.productmanager.service.impl;

import com.shawn.springboot.integeration.redis.productmanager.model.pojo.Product;
import com.shawn.springboot.integeration.redis.productmanager.service.IProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author zhangjian
 * @description: 产品服务接口实现
 * @date 2022/8/20
 */
@Service
public class ProductServiceImpl implements IProductService {
    private Logger log = LoggerFactory.getLogger(ProductServiceImpl.class);

    //测试数据
    private static final HashMap<String, Product> stringProductHashMap = new HashMap<>();

    static {
        stringProductHashMap.put("1", new Product("1", "手机"));
        stringProductHashMap.put("2", new Product("2", "笔记本"));
        stringProductHashMap.put("3", new Product("3", "电脑"));
        stringProductHashMap.put("4", new Product("4", "飞机"));
    }

    /**
     * 查询产品,若缓存中不存在,则查询后放入缓存,若缓存中存在,则从缓存中获取
     *
     * @param id
     * @return
     */
    @Cacheable(value = {"product"}, key = "#id")
    @Override
    public Product select(String id) {
        Product product = stringProductHashMap.get(id);
        log.info("从 DB 中查询产品:[{}]", id);
        return product;
    }

    /**
     * 新增或者修改
     *
     * @param product
     * @return
     */
    @CachePut(value = "product", key = "#product.id")
    @Override
    public Product saveOrUpdate(Product product) {
        stringProductHashMap.put(product.getId().toString(), product);
        log.info("从 DB 中更新产品:[{}]", product.getId());
        return product;
    }

    /**
     * 删除
     *
     * @param id
     */
    @CacheEvict(value = "product", key = "#id")
    @Override
    public void delete(String id) {
        stringProductHashMap.remove(id);
        log.info("从 DB 中删除产品:[{}]", id);
    }
}
